package cn.jg.framework.common.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;
import org.apache.ibatis.logging.LogFactory;
import org.slf4j.Marker;

/**
 * Created by luowei on 2020/8/24.
 */
public class MybatisSqlLogFilter extends Filter<ILoggingEvent> {

	private static final String MYBATIS_MARKER = LogFactory.MARKER;
	private static final String HIDE_SQL_PATTERN = "==>  Preparing:";

	private boolean disabled = true;

	public void setDisabled(boolean disabled) {
		this.disabled = disabled;
	}

	@Override
	public FilterReply decide(ILoggingEvent event) {
		if (!isStarted()) {
			return FilterReply.NEUTRAL;
		}
		Marker marker = event.getMarker();
		if (disabled && marker != null
				&& MYBATIS_MARKER.equals(marker.getName())
				&& event.getMessage() != null
				&& event.getMessage().startsWith(HIDE_SQL_PATTERN)) {
			return FilterReply.DENY;
		} else {
			return FilterReply.NEUTRAL;
		}
	}
}
